import axios from "axios";

//这个东西 表示每次请求可以携带 cookie 和 session
// 带上可能会跨域
axios.defaults.withCredentials = true;

axios.interceptors.request.use(
    (config) =>{
    let token = 'Bear ';
    if (token){
        //config.headers.Authorization = token;
    }
    return config;
})

axios.interceptors.response.use(
    function (response){
        // 暂时不做处理，直接返回
        return response;
    },function (error) {
        return Promise.reject(error);
    }
)

const base = window._CONFIG['apiURL'];

function getUrl(url){
    if (!url){
        console.log('请求的url不可为空');
        return;
    }
    if (url.indexOf('http') > -1){
        return url;
    }else {
        return `${base}${url}`;
    }
}

export const GET = (url,params)=>{
    return axios.get(getUrl(url), {
        params: params}
    ).then((res) => res.data)
};

export const POST = (url,params) =>{
    return axios.post(getUrl(url),params,{
        headers:{
            "Content-Type": 'application/json'
        }
    }).then(res => res.data);
};

export const PUT = (url,params) =>{
    return axios.put(getUrl(url),params)
        .then(res => res.data);
};

export const DELETE = (url,params) =>{
    return axios.delete(getUrl(url),{
        params: params
    })
        .then(res => res.data);
}

export const DOWNLOAD = (url,params) =>{
    return axios.get(getUrl(url),{
        params: params,
        responseType: "blob"
    })
        .then(res => res.data)
}

export const DOWNLOAD_FILE = (url,params,fileName) =>{
    return axios.get(getUrl(url),{
        params: params,
        responseType: "blob"
    })
        .then(res => {
            let blob = new Blob([res.data],{type:'application/vnd.ms-excel'});
            let documentElement = document.createElement("a");
            let href = URL.createObjectURL(blob);
            documentElement.href = href;
            documentElement.download = fileName;
            document.body.appendChild(documentElement);
            documentElement.click();
            document.body.removeChild(documentElement);
            URL.revokeObjectURL(href);
        })
};

export const downloadByPost = (url, params) => {
    return axios
        .post(getUrl(url), params, {
            responseType: "blob",
        })
        .then((res) => res.data);
};
